package com.miet.mp45.filippov.cryptoapplet.actionpanels;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JFileChooser;

import org.apache.log4j.Logger;

import com.miet.mp45.filippov.crypto.util.CryptoUtil;
import com.miet.mp45.filippov.cryptoapplet.actionpanels.events.ProcessingFinishedEventListener;
import com.miet.mp45.filippov.cryptoapplet.actionpanels.events.ProcessingStartedEventListener;
import com.miet.mp45.filippov.utils.IOUtilities;

public class ExpractPanel extends ActionPanel
{

    private static final long serialVersionUID = -2520478427719420173L;

    private Logger logger = Logger.getLogger(this.getClass());
    private javax.swing.JButton browseButton;
    private javax.swing.JButton separateButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField filePathTextField;
    
    
    public ExpractPanel(ProcessingStartedEventListener pseListener,
                         ProcessingFinishedEventListener pfeListener)
    {
        addPSEListener(pseListener);
        addPFEListener(pfeListener);
        initComponents();
    }

    private void initComponents()
    {

        jLabel1 = new javax.swing.JLabel();
        filePathTextField = new javax.swing.JTextField();
        browseButton = new javax.swing.JButton();
        separateButton = new javax.swing.JButton();

        jLabel1.setText("KeyPair Path:");

        browseButton.setText("...");
        browseButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                browseButtonActionPerformed(evt);
            }
        });

        separateButton.setText("Separate");
        separateButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                separateButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        setLayout(layout);
        layout
                .setHorizontalGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(
                                layout
                                        .createSequentialGroup()
                                        .addContainerGap()
                                        .addGroup(
                                                layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.LEADING,
                                                                false)
                                                        .addGroup(
                                                                layout
                                                                        .createSequentialGroup()
                                                                        .addComponent(jLabel1)
                                                                        .addPreferredGap(
                                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                        .addComponent(
                                                                                filePathTextField,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                224,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                        .addPreferredGap(
                                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                        .addComponent(browseButton))
                                                        .addComponent(
                                                                separateButton,
                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                Short.MAX_VALUE)).addContainerGap(
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addContainerGap().addGroup(
                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel1).addComponent(filePathTextField,
                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(
                                        browseButton)).addPreferredGap(
                        javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(
                        separateButton).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
                        Short.MAX_VALUE)));

    }

    private void separateButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        if (!filePathTextField.getText().isEmpty())
        {
            FILE_CHOOSER.setFileFilter(PUBLIC_KEY_FILE_FILTER);
            if (FILE_CHOOSER.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
            {
                new CryptoTask()
                {
                    @Override
                    public void doRun()
                    {
                        FileOutputStream fos = null;
                        try
                        {
                            File file = FILE_CHOOSER.getSelectedFile();
                            byte[] encodedPrivateKey = IOUtilities.readFile(filePathTextField.getText());
                            logger.info("Separating public key ...");
                            byte[] publicKey = CryptoUtil.extractPublicKey(encodedPrivateKey);
                            logger.info("Writing public key into '" + file + "'");
                            fos = new FileOutputStream(file);
                            fos.write(publicKey);
                        }
                        catch (Exception ex)
                        {
                            logger.error(ex);
                        }
                        finally
                        {
                            if (fos != null)
                            {
                                try { fos.close(); } catch (IOException ex) { logger.error(ex); }
                            }
                        }
                    }
                }.start();
            }
        }    
    }

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        FILE_CHOOSER.setFileFilter(PRIVATE_KEY_FILE_FILTER);
        if (FILE_CHOOSER.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
        {
            filePathTextField.setText(FILE_CHOOSER.getSelectedFile().getAbsolutePath());
        }
    }

}
